<template>
  <div class="created-form-content">
    <div class="created-form-top">表单 ( 创建 / 新增 )</div>
    <div class="created-form-bottom">
      <div class="content">
        <ProForm
          ref="proFormBox"
          :select-index="basicForm.selectedIndex"
          v-model:options="basicForm.options"
          :form-attrs="basicForm.formAttrs"
          :save-button="false"
          @get-model="form => (basicForm.form = form)"
        >
          <template #operationItem="{ item, index }">
            <div>
              <SvgIcon class="svg-copyAdd" name="copyAdd" @click.stop.prevent="copyItem(item, index)"></SvgIcon>
            </div>
            <div>
              <SvgIcon class="svg-del" name="del" @click.stop.prevent="deleteItem(index)"></SvgIcon>
            </div>
          </template>
        </ProForm>
      </div>
    </div>
  </div>
  <div class="created-form-right">
    <div class="content">
      <Right :options="basicForm.options" ref="rightRef"></Right>
    </div>
    <div class="button">
      <el-button type="primary" @click="saveForm" :loading="globalStore.formLoading">保存</el-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { CustomForm, OptionsProps } from '@/components/ProForm/interface';
import ProForm from './ProForm/index.vue';
import { cloneDeep } from 'lodash';
import { setNestedValue } from '@/utils/operationObject';
import Right from '../right/index.vue';
let rightRef = ref(null);

export interface CreatedFormCustomFormProp extends CustomForm {
  selectedIndex: number;
  selectItem?: any;
  options: CreatedFormOptionsProps[];
}

export interface CreatedFormOptionsProps extends OptionsProps {
  itemOptions?: CreatedFormOptionsProps[];
}

const proFormBox = ref();

const globalStore = useGlobalStore();

let basicForm = reactive<CreatedFormCustomFormProp>({
  selectedIndex: 1,
  form: {},
  formAttrs: {},
  title: '',
  visible: false,
  transitionArr: [],
  options: []
});
const copyItem = (item, index) => {
  console.log('???????', item, index);

  const _item = cloneDeep(item);
  const prop = `${item.prop}-${basicForm.options.length}`;
  // 同步编辑时内容
  if (_item?.itemOptions) {
    for (let op of _item.itemOptions) {
      if (op.prop === 'prop') {
        op.defaultValue = prop;
        break;
      }
    }
  }
  const newObj = {
    ..._item,
    prop
  };
  // 插入到当前位置
  basicForm.options.splice(index + 1, 0, cloneDeep(newObj));

  // basicForm.options.push(cloneDeep(newObj));
};

const deleteItem = (index: number) => {
  useHandleData(
    () => {
      basicForm.options.splice(index, 1);
      basicForm.selectedIndex = -1;
    },
    null,
    `删除表单项`,
    null
  );
};

let tableId = ref<any>(0);
const route = useRoute();
watch(
  () => route.fullPath,
  () => {
    init(true);
  }
);

onBeforeMount(() => init());

onMounted(() => {
  /**
   * customerForm 客户新增
   * customerAddrForm 客户地址新增
   * customerContactForm 客户联系人新增
   */

  mittBus.on('crated-form-right', setFormItemValue);
});
const init = async (flag?: boolean) => {
  // const form = localGet("page_form2");
  const { id } = route.query;

  if (id) {
    tableId.value = id;
    const data: any = await pageJsonConfigFind(id);
    if (data) {
      const p = JSON.parse(data.json);
      // console.log(p, 'p');

      Object.assign(rightRef.value.overallForm.form, p.overallForm);
      Object.assign(basicForm, p.basicForm);
      // console.log(rightRef.value.overallForm.form, 'rightRef.value.overallForm.form');
    }
  } else {
    // 直接刷新页面
    if (flag) {
      window.location.reload();
    }
  }
};

onUnmounted(() => {
  mittBus.off('crated-form-right', setFormItemValue);
});

/**设置表单项内容 */
const setFormItemValue = itemForm => {
  for (let item of itemForm.options) {
    if (item.prop === 'attrs.multiple') {
      const multiple = itemForm.form[item.prop];
      basicForm.form[basicForm.options[itemForm.selectedIndex].prop] = multiple ? [] : '';
      nextTick(() => {
        basicForm.options[itemForm.selectedIndex].attrs.multiple = itemForm.form[item.prop];
      });
    } else {
      setNestedValue(basicForm.options[itemForm.selectedIndex], item.prop, itemForm.form[item.prop]);
    }
  }

  basicForm.options[itemForm.selectedIndex].itemOptions = cloneDeep(itemForm.options);
  // 验证规则字段对应不上需要手动设置规则
  basicForm.options[itemForm.selectedIndex].rules = itemForm.form.rules;
  // console.log(basicForm, 'basicForm', itemForm);
};

const saveForm = async () => {
  let options = [];
  for (let op of basicForm.options) {
    const item = {
      rules: []
    };
    if (!op?.itemOptions) {
      elMessage(`表单项${op.label}没有完善过请先完善在保存`, 'warning');
      return;
    }
    for (let v of op.itemOptions) {
      setNestedValue(item, v.prop as string, v.defaultValue);
    }
    item.rules = op.rules;
    options.push(item);
  }

  let useForm = {
    options: []
  };
  const { form } = rightRef.value.overallForm || {};

  Object.keys(form).forEach(key => {
    setNestedValue(useForm, key, form[key]);
  });

  // 需要使用的表单
  useForm.options = options;
  const jsonParams = {
    useForm,
    overallForm: form,
    basicForm
  };

  const params = {
    cname: form.formName,
    type: 'form',
    id: tableId.value || '',
    json: JSON.stringify(jsonParams)
  };
  console.log(params, 'params', jsonParams);
  globalStore.formLoading = true;
  const backForm = !tableId.value ? await pageJsonConfigSave(params) : await pageJsonConfigUpdate(params);

  elMessage();
  routerPush(route.path, { id: backForm.id });
};

defineExpose({
  basicForm
});
</script>
<style lang="scss" scoped src="./index.scss"></style>
<style lang="scss"></style>
@/utils/operationObject
